import 'dart:collection';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zhibao_flutter/pages/other/home_without_internet_page.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/float/float_widget.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/widget/appbar/commom_bar.dart';
import 'package:zhibao_flutter/widget/fun/check_double_exit.dart';
import 'package:zhibao_flutter/zone.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

class WebViewPage extends StatefulWidget {
  final String? link;
  final bool showAppBar;
  final bool mainPage;
  final RxInt? currentIndex;

  WebViewPage(
      {this.link,
      this.showAppBar = true,
      this.mainPage = false,
      this.currentIndex});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage>
    with AutomaticKeepAliveClientMixin {
  bool netErrorState = false;
  bool netErrorStateStore = false;

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewSettings settings = InAppWebViewSettings(
    // useShouldOverrideUrlLoading: true,
    // mediaPlaybackRequiresUserGesture: false,
    javaScriptCanOpenWindowsAutomatically: true,
    javaScriptEnabled: true,
    // useHybridComposition: true,
  );

  // InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
  //     crossPlatform: InAppWebViewOptions(
  //         useShouldOverrideUrlLoading: true,
  //         mediaPlaybackRequiresUserGesture: false),
  //     android: AndroidInAppWebViewOptions(
  //       useHybridComposition: true,
  //       mixedContentMode: AndroidMixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
  //     ),
  //     ios: IOSInAppWebViewOptions(
  //       allowsInlineMediaPlayback: true,
  //     ),);

  late PullToRefreshController pullToRefreshController;
  String url = "";
  double progress = 0;
  final urlController = TextEditingController();
  final inAppWebviewKeepAlive = InAppWebViewKeepAlive();
  bool nextKickBackExitApp = false;

  void setErrorOfNet() {
    netErrorStateStore = true;
    netErrorState = true;
    setState(() {});
  }

  void resetOfNet() {
    netErrorState = false;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    if (widget.mainPage) {
      widget.currentIndex!.stream.listen((event) {
        LogUtil.d("widget.currentIndex!.value::${widget.currentIndex!.value}");
        if (widget.currentIndex!.value != 2) {
          webViewController?.pause();
        } else {
          webViewController?.resume();
        }
      });
    }
    pullToRefreshController = PullToRefreshController(
      settings: PullToRefreshSettings(color: MyTheme.mainColor.value),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<bool> onWillPop() async {
    if (nextKickBackExitApp) {
      return Future<bool>.value(true);
    } else {
      myToast('exitApp'.tr);
      nextKickBackExitApp = true;
      Future.delayed(
        const Duration(seconds: 2),
        () => nextKickBackExitApp = false,
      );
      return Future<bool>.value(false);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    String? linkUrl = widget.link ?? Get.arguments?['linkUrl'];
    final body = MyScaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      appBar: widget.showAppBar ? CommomBar() : null,
      body: SafeArea(
        top: true,
        bottom: false,
        child: !strNoEmpty(linkUrl)
            ? Center(child: Text('linkError'.tr))
            : Stack(
                children: [
                  InAppWebView(
                    key: webViewKey,
                    keepAlive: inAppWebviewKeepAlive,
                    initialUrlRequest: URLRequest(url: WebUri(linkUrl!)),
                    initialUserScripts: UnmodifiableListView<UserScript>([]),
                    // initialOptions: options,
                    initialSettings: settings,
                    shouldOverrideUrlLoading: (controller, request) async {
                      var uri = request.request.url!.uriValue;
                      LogUtil.d("we well jump to ${uri.toString()}");
                      if (uri.toString().contains("qq.com")) {
                        myToast("chooseLogin".tr);
                        return NavigationActionPolicy.CANCEL;
                      }

                      if (![
                        "http",
                        "https",
                        "file",
                        "chrome",
                        "data",
                        "javascript",
                        "about"
                      ].contains(uri.scheme)) {
                        // if (await canLaunchUrl(uri)) {
                        LogUtil.d("Open the url ::${uri.toString()}");
                        // Launch the App
                        try {
                          await launchUrl(uri,
                              mode: LaunchMode.externalNonBrowserApplication);
                        } catch (e) {
                          LogUtil.d("Error::${e.toString()}");
                        }
                        // and cancel the request
                        return NavigationActionPolicy.CANCEL;
                        // }
                      }

                      return NavigationActionPolicy.ALLOW;
                    },
                    pullToRefreshController: pullToRefreshController,
                    onWebViewCreated: (controller) {
                      webViewController = controller;
                    },
                    onLoadStart: (controller, url) {
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onPermissionRequest: (controller, permissionRequest) async {
                      return PermissionResponse(
                          resources: permissionRequest.resources,
                          action: PermissionResponseAction.GRANT);
                    },
                    // androidOnPermissionRequest:
                    //     (controller, origin, resources) async {
                    //   return PermissionRequestResponse(
                    //       resources: resources,
                    //       action: PermissionRequestResponseAction.GRANT);
                    // },
                    onLoadStop: (controller, url) async {
                      pullToRefreshController.endRefreshing();
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onLoadError: (controller, url, code, message) {
                      pullToRefreshController.endRefreshing();

                      LogUtil.d(
                          "[InAppWebView] onLoadHttpError::statusCode::$code,,,$message,");
                      setErrorOfNet();
                    },
                    onProgressChanged: (controller, progress) {
                      LogUtil.d(
                          "progress::$progress，netErrorStateStore::$netErrorStateStore");

                      if (progress == 100) {
                        if (!netErrorStateStore) {
                          resetOfNet();
                        }
                        pullToRefreshController.endRefreshing();
                      }
                      setState(() {
                        this.progress = progress / 100;
                        urlController.text = this.url;
                      });
                    },
                    onUpdateVisitedHistory: (controller, url, androidIsReload) {
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      print("""
                        -----------
                        $consoleMessage
                        -----------
                        """);
                    },
                    onLoadHttpError: (InAppWebViewController controller,
                        Uri? url, int statusCode, String description) {
                      LogUtil.d(
                          "[InAppWebView] onLoadHttpError::statusCode::$statusCode,,,$description,");
                      setErrorOfNet();
                    },
                  ),
                  if (netErrorState)
                    Container(
                      color: Colors.white,
                      child: HomeWithoutInternetPage(
                        () {
                          netErrorStateStore = false;
                          webViewController?.reload();
                        },
                        topMargin: 10,
                      ),
                    ),
                  progress < 1.0
                      ? LinearProgressIndicator(value: progress)
                      : Container(),
                  FloatWidget(() {
                    webViewController?.loadUrl(
                        urlRequest:
                            URLRequest(url: WebUri.uri(Uri.parse(linkUrl!))));
                  })
                ],
              ),
      ),
    );
    if (!widget.mainPage || widget.currentIndex?.value == 2) {
      return WillPopScope(
        // canPop: false,
        onWillPop: () async {
          LogUtil.d("WillPopScope");
          // print("PopScope::did::$did");
          if ((await webViewController?.canGoBack()) ?? false) {
            webViewController?.goBack();
            return Future<bool>.value(false);
          }
          if (widget.mainPage) {
            return onWillPop();
          }
          return Future<bool>.value(true);
        },
        child: body,
      );
    }
    return body;
  }

  @override
  bool get wantKeepAlive => true;
}
